package com.yeskery.nut.util;

/**
 * String 的工具类
 * @author sprout
 * 2019-03-14 09:21
 * @version 1.0
 */
public class StringUtils {

	/** 扩展分隔符 */
	private static final char EXTENSION_SEPARATOR = '.';

	/** 路径分隔符 */
	private static final String FOLDER_SEPARATOR = "/";

	/** 分组分隔符 */
	private static final String GROUP_SEPARATOR = "-";

	/**
	 * 私有化构造方法
	 */
	private StringUtils() {
	}

	/**
	 * 判断字符串是否为空
	 * @param str 字符串
	 * @return 是否为空
	 */
	public static boolean isEmpty(String str) {
		return str == null || str.isEmpty();
	}

	/**
	 * 判断字符串是否为空字符串
	 * @param str 字符串
	 * @return 是否为空
	 */
	public static boolean isBlank(String str) {
		return str == null || str.trim().isEmpty();
	}

	/**
	 * 获取文件后缀名
	 * @param path 路径
	 * @return 文件后缀名
	 */
	public static String getFilenameExtension(String path) {
		if (isEmpty(path)) {
			return null;
		}

		int extIndex = path.lastIndexOf(EXTENSION_SEPARATOR);
		if (extIndex == -1) {
			return null;
		}

		int folderIndex = path.lastIndexOf(FOLDER_SEPARATOR);
		if (folderIndex > extIndex) {
			return null;
		}

		return path.substring(extIndex + 1);
	}

	/**
	 * 获取文件后缀名
	 * @param path 路径
	 * @return 文件后缀名
	 */
	public static String getFilename(String path) {
		if (path == null) {
			return null;
		} else if (path.isEmpty()){
			return path;
		}

		int folderIndex = path.lastIndexOf(FOLDER_SEPARATOR);
		if (folderIndex == -1) {
			return path;
		}

		return path.substring(folderIndex + 1);
	}

	/**
	 * 获取key的分隔符数量
	 * @param key key
	 * @param separator 分隔符
	 * @return key的分隔符数量
	 */
	public static int getKeySeparatorSize(String key, String separator) {
		if (StringUtils.isEmpty(key)) {
			return 0;
		}
		int size = 0, index = -1;
		while ((index = key.indexOf(separator, index + 1)) != -1) {
			size++;
		}
		return size;
	}

	/**
	 * 获取处理后的分隔符名称
	 * @param name 名称
	 * @return 处理后的分隔符名称
	 */
	public static String getModifyName(String name) {
		if (name == null || !name.contains(GROUP_SEPARATOR)) {
			return name;
		}

		while (name.contains(GROUP_SEPARATOR + GROUP_SEPARATOR)) {
			name = name.replace(GROUP_SEPARATOR + GROUP_SEPARATOR, GROUP_SEPARATOR);
		}
		if (!StringUtils.isEmpty(name) && name.startsWith(GROUP_SEPARATOR)) {
			name = name.substring(1);
		}
		if (!StringUtils.isEmpty(name) && name.endsWith(GROUP_SEPARATOR)) {
			name = name.substring(0, name.length() - 1);
		}
		if (name.length() == 1) {
			return name;
		}

		StringBuilder sb = new StringBuilder();
		String[] splits = name.split(GROUP_SEPARATOR);
		for (int i = 0; i < splits.length; i++) {
			String str = splits[i].trim();
			if (StringUtils.isEmpty(str)) {
				continue;
			}
			if (i == 0) {
				sb.append(str);
			} else {
				sb.append(str.substring(0, 1).toUpperCase()).append(str.substring(1));
			}
		}
		return sb.toString();
	}
}
